package com.yjlove.myplay.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.AMapNavi;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.yjlove.myplay.Navi.MyPoiOverlay;
import com.yjlove.myplay.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 作者 YJlvoe
 * 创建时间 2016/12/5.
 */
public class AMapTestActivity extends AppCompatActivity implements View.OnClickListener, LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener, TextWatcher {

    private static final String TAG = "AMapTestActivity";
    @Bind(R.id.btn_normal)
    Button mBtnNormal;
    @Bind(R.id.btn_satellite)
    Button mBtnSatellite;
    @Bind(R.id.btn_night)
    Button mBtnNight;
    @Bind(R.id.actv_address)
    AutoCompleteTextView mActvAddress;
    @Bind(R.id.btn_search)
    Button mBtnSearch;
    @Bind(R.id.btn_cannel)
    Button mBtnCannel;
    @Bind(R.id.lv_result)
    ListView mLvResult;
    @Bind(R.id.ll_result)
    LinearLayout mLlResult;

    private MapView mMapView = null;// 获取地图控件
    private AMap mAMap = null;// 定义地图对象
    private UiSettings mUiSettings = null;//定义一个UiSettings对象


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    // 定位监听
    public OnLocationChangedListener mListener;
    // 声明导航对象
    private AMapNavi mAMapNavi;

    // 声明搜索相关对象
    private PoiSearch.Query mQuery;
    private PoiSearch mPoiSearch;
    private PoiResult mPoiResult;

    // 文本模糊查询列表
    private ArrayList<String> list = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amtest);
        ButterKnife.bind(this);

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);

        initView();
        initData();
    }

    private void initView() {

        if (mAMap == null) {
            mAMap = mMapView.getMap();
        }
        mAMap.setMapType(AMap.MAP_TYPE_NORMAL);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(17));//将地图的缩放级别调整到17级

        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.setMyLocationEnabled(true);// 可触发定位并显示定位层

        //获取AMapNavi实例导航
        mAMapNavi = AMapNavi.getInstance(getApplicationContext());
        //添加监听
        //mAMapNavi.addAMapNaviListener(this);

        showMapType();// 调用地图样式方法
        locationMethod();// 调用定位方法

        mBtnNormal.setOnClickListener(this);
        mBtnSatellite.setOnClickListener(this);
        mBtnNight.setOnClickListener(this);
        mBtnSearch.setOnClickListener(this);
        mBtnCannel.setOnClickListener(this);

        mActvAddress.addTextChangedListener(this);
    }

    private void initData() {
    }

    /**
     * 显示地图的控件UI样式
     */
    private void showMapType() {
        mUiSettings = mAMap.getUiSettings();//实例化UiSettings类
        mUiSettings.setZoomControlsEnabled(false);// 不显示缩放按钮
        mUiSettings.setCompassEnabled(true);//显示指南针
        mUiSettings.setMyLocationButtonEnabled(true); // 显示默认的定位按钮

        mUiSettings.isMyLocationButtonEnabled();// 显示当前位置
    }

    /**
     * 定位方法
     */
    private void locationMethod() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //获取一次定位结果：该方法默认为false。
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    // 实现定位接口
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        boolean isFirstLoc = true;

        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码

                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    //将地图移动到定位点
                    mAMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(aMapLocation.getCountry() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getCity() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getDistrict() + ""
                            + aMapLocation.getStreet() + ""
                            + aMapLocation.getStreetNum());
                    Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                    isFirstLoc = false;
                }
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    /**
     * 搜索位置方法
     */
    private void doSearch() {
        mQuery = new PoiSearch.Query(mActvAddress.getText().toString(), "", "北京");
        mQuery.setPageSize(10);
        mQuery.setPageNum(0);

        mPoiSearch = new PoiSearch(this, mQuery);
        mPoiSearch.setOnPoiSearchListener(this);
        mPoiSearch.searchPOIAsyn();
    }

    /**
     * 实现位置搜索功能接口
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 0) {
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(mQuery)) {
                    mPoiResult = result;

                    List<PoiItem> poiItems = mPoiResult.getPois();
                    List<SuggestionCity> suggestionCities = mPoiResult
                            .getSearchSuggestionCitys();

                    if (poiItems != null && poiItems.size() > 0) {

                        MyPoiOverlay myPoiOverlay = new MyPoiOverlay(mAMap, poiItems);
                        myPoiOverlay.removeFromMap();
                        myPoiOverlay.addToMap();
                        myPoiOverlay.zoomToSpan();

                        for (int i = 0; i < poiItems.size(); i++) {
                            list.add(" " + (i + 1) + "." + poiItems.get(i).toString());
                        }

                        /*Log.i("get information",poiItems.get(1).getSnippet());
                        Log.i("get information",poiItems.get(1).getDirection());
                        Log.i("get information",poiItems.get(1).getAdName());
                        Log.i("get information",poiItems.get(1).toString());*/

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                R.layout.item_amtest, list);
                        mLvResult.setAdapter(adapter);

                    } else {
                        Log.i(TAG, "onPoiSearched error");
                    }
                }
            }
        } else {
            Log.i(TAG, "onSearchPoi + rcode = " + rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 实现位置模糊搜索功能接口
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        Inputtips inputtips = new Inputtips(this, new Inputtips.InputtipsListener() {
            @Override
            public void onGetInputtips(List<Tip> tipList, int rcode) {
                if (rcode == 0 ){
                    List<String> listString = new ArrayList<String>();
                    for (int i = 0; i < tipList.size(); i++) {
                        listString.add(tipList.get(i).getName());
                    }
                    ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
                            getApplicationContext(),
                            R.layout.inputs_amtest, listString);
                    mActvAddress.setAdapter(aAdapter);
                    aAdapter.notifyDataSetChanged();
                }
            }
        });
        try {
            inputtips.requestInputtips(newText,"北京");
        } catch (AMapException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private int searchState = 0;

    /**
     * 处理界面按钮
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_normal:
                mAMap.setMapType(AMap.MAP_TYPE_NORMAL);
                break;
            case R.id.btn_satellite:
                mAMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.btn_night:
                mAMap.setMapType(AMap.MAP_TYPE_NIGHT);
                break;
            case R.id.btn_search:
                list.clear();
                if (!mActvAddress.getText().toString().equals("")) {
                    doSearch();
                    searchState = 1;
                    if(mLlResult.getVisibility() == View.GONE){
                        mLlResult.setVisibility(View.VISIBLE);
                    }else if (mLlResult.getVisibility() == View.VISIBLE){
                        //layout.setVisibility(View.GONE);
                    }
                } else {
                    new AlertDialog.Builder(this)
                            .setTitle("地图")
                            .setMessage("请输入内容")
                            .setPositiveButton("ok", null)
                            .show();
                }
                break;
            case R.id.btn_cannel:

                break;
        }
    }

    /**
     * 处理生命周期
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }
}